﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.DAL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class AC_Activitys : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        IJobSiteBLL jsBLL = new JobSiteBLL();
        IEmployeeBLL empBLL = new EmployeeBLL();
        IMasCityBLL cityBLL = new MasCityBLL();
        ActivityTypeBLL AcBLL = new ActivityTypeBLL();
        ActivityBLL actBLL = new ActivityBLL();
        BgmProjectBLL bgmProjBLL = new BgmProjectBLL();
        ActivityRequestBLL ActReqBLL = new ActivityRequestBLL();

        private const int ItemsPerRequest = 10;
        protected void Page_Load(object sender, EventArgs e)
        {
            txtAct_Limit.Attributes.Add("onkeypress", "return isNumberKey(event)");

            if (!IsPostBack)
            {
                LoadActType();
                FillDataToJobSite();
                cmbWorkingJobSite.SelectedValue = GetWorkingJobSite(); 
                LoadDataGrid();                
            }
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        private void LoadDataGrid()
        {
            Nullable<int> JobSiteSeq = string.IsNullOrEmpty(cmbWorkingJobSite.SelectedValue) ? (int?)null : Int32.Parse(cmbWorkingJobSite.SelectedValue);
            Nullable<DateTime> DateStart = string.IsNullOrEmpty(txtStart.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtStart.GetStringValue());
            Nullable<DateTime> DateEnd = string.IsNullOrEmpty(txtEnd.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtEnd.GetStringValue());

            DataSet ds = actBLL.LoadActivity((int?)null, JobSiteSeq, DateStart, DateEnd);
            DataTable table = null;
            if (ds.Tables.Count > 0)
            {
                table = ds.Tables[0];
            }
            RadGrid1.DataSource = table;
            RadGrid1.DataBind();
        }

        private void LoadActType()
        {
            DataSet ListDataCommand = AcBLL.GetDataAcType("");
            DataTable table = ListDataCommand.Tables[0];
            cbActivityType.DataSource = ListDataCommand.Tables[0];
            cbActivityType.DataBind();

        }

        protected void FillDataToJobSite()
        {
            DataSet ds = jsBLL.LoadJobSites("", SystemInfo._JobsiteInternal, "", "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }

            cmbWorkingJobSite.DataSource = dt;
            cmbWorkingJobSite.DataBind();
        }
        protected string GetWorkingJobSite()
        {
            string WorkingJobSite = "";

            DataSet ds = empBLL.LoadEmployees(ssMng.EmpSeqI, "", true, "");
            DataTable dt = null;
            if (ds != null)
            {
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    WorkingJobSite = dt.Rows[0]["WORKING_JOB_SITE_SEQ"].ToString();
            }

            return WorkingJobSite;
        }
        protected void cmbProject_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            Nullable<int> JobSiteSeq = string.IsNullOrEmpty(cmbWorkingJobSite.SelectedValue) ? (int?)null : Int32.Parse(cmbWorkingJobSite.SelectedValue);
            cmbProject.Items.Clear();

            DataSet ds = bgmProjBLL.LoadBgmProjects((int?)null, JobSiteSeq, (int?)null, (int?)null, e.Text);
            DataTable dt = ds.Tables[0];

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbProject.Items.Add(new RadComboBoxItem(dt.Rows[i]["BGM_PROJ_OPER_NAME"].ToString(), dt.Rows[i]["BGM_PROJ_OPER_SEQ"].ToString()));

                TableRow tr = new TableRow();

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["BGM_PROJ_OPER_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(350);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                ((Table)cmbProject.Items[j].FindControl("tableProject")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }
        protected void cmbCity_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbCity.Items.Clear();

            DataSet ds = cityBLL.LoadMasCities((int?)null, (int?)null);
            DataTable dt = ds.Tables[0];

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbCity.Items.Add(new RadComboBoxItem(dt.Rows[i]["CITY_NAME"].ToString() + " ประเทศ" + dt.Rows[i]["COUNTRY_NAME"].ToString(), dt.Rows[i]["CITY_SEQ"].ToString()));

                TableRow tr = new TableRow();

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["CITY_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(150);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                TableCell tdCountryName = new TableCell();
                Label lblCountryName = new Label();
                lblCountryName.Text = dt.Rows[i]["COUNTRY_NAME"].ToString();
                tdCountryName.Width = Unit.Pixel(200);
                tdCountryName.Controls.Add(lblCountryName);
                tr.Cells.Add(tdPosName);

                ((Table)cmbCity.Items[j].FindControl("tableCity")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }
        protected void cmbJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            cmbJobSite.Items.Clear();

            DataSet ds = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "3", e.Text);
            DataTable dt = ds.Tables[0];

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbJobSite.Items.Add(new RadComboBoxItem(dt.Rows[i]["JOB_SITE_NAME"].ToString(), dt.Rows[i]["JOB_SITE_SEQ"].ToString()));

                TableRow tr = new TableRow();

                TableCell tdPosName = new TableCell();
                Label lblPosName = new Label();
                lblPosName.Text = dt.Rows[i]["JOB_SITE_NAME"].ToString();
                tdPosName.Width = Unit.Pixel(350);
                tdPosName.Controls.Add(lblPosName);
                tr.Cells.Add(tdPosName);

                ((Table)cmbJobSite.Items[j].FindControl("tableJobSite")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }
        protected void RadGrid1_ItemCommand(object o, GridCommandEventArgs e)
        {
            if (e.CommandName == "AddData")
            {
                UpdateUI("AddNew");

            }
            else if (e.CommandName == "DataEdit")
            {
                UpdateUI("Update");

                int Sequence = Int32.Parse(RadGrid1.Items[e.Item.ItemIndex]["act_seq"].Text);
                DataSet ListDataCommand = actBLL.LoadActivity(Sequence, (int?)null, (DateTime?)null, (DateTime?)null);
                if (ListDataCommand.Tables.Count > 0)
                {
                    DataTable table = ListDataCommand.Tables[0];
                    if (table.Rows.Count > 0)
                    {
                        txtActivitySeq.Text = table.Rows[0]["act_seq"].ToString();
                        cmbProject.Items.Add(new RadComboBoxItem(table.Rows[0]["BGM_PROJ_OPER_NAME"].ToString(), table.Rows[0]["BGM_PROJ_OPER_SEQ"].ToString()));
                        //txtActivityDesc.Text = table.Rows[0]["act_descr"].ToString();
                        cbActivityType.SelectedValue = table.Rows[0]["act_type_seq"].ToString();
                        cmbJobSite.Items.Add(new RadComboBoxItem(table.Rows[0]["JOB_SITE_NAME"].ToString(), table.Rows[0]["JOB_SITE_SEQ"].ToString()));

                        cmbJobSite.SelectedValue = table.Rows[0]["job_site_seq"].ToString();
                        cmbCity.SelectedValue = table.Rows[0]["city_seq"].ToString();
                        txtLocation.Text = table.Rows[0]["location_text"].ToString();
                        txtDateSignStart.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_sign_start"]));
                        txtDateSignEnd.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_sign_end"]));
                        txtTimeSignEnd.Text = table.Rows[0]["time_sign_end"].ToString();
                        txtDateStart.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_activity_start"]));
                        txtDateEnd.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_activity_end"]));
                        txtAppDateStart.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_app_start"]));
                        txtAppDateEnd.SetValue(string.Format("{0:dd/MM/yyyy}", table.Rows[0]["date_app_end"]));
                        txtAct_Limit.Text = table.Rows[0]["act_limit"].ToString();
                        txtAttendCount.Text = table.Rows[0]["attend_count"].ToString();
                        txtRemark.Text = table.Rows[0]["remarks"].ToString();
                    }
                }
            }
            else if (e.CommandName == "Delete")
            {
                string Sequence = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["act_seq"].ToString();

                actBLL.Delete(Sequence, ssMng.EmpSeq);
                UpdateUI("Save");

            }
            LoadDataGrid();
        }
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            LoadDataGrid();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            actBLL.Insert(Int32.Parse(cmbProject.SelectedValue)
                , "" //txtActivityDesc.Text
                , cbActivityType.SelectedValue
                , cmbJobSite.SelectedValue
                , txtAct_Limit.Text
                , string.IsNullOrEmpty(txtDateSignStart.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtDateSignStart.GetStringValue())
                , txtAppDateStart.GetDateValue()
                , txtAppDateEnd.GetDateValue()
                , string.IsNullOrEmpty(txtDateSignEnd.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtDateSignEnd.GetStringValue())
                , txtDateStart.GetDateValue()
                , txtDateEnd.GetDateValue()
                , txtTimeSignEnd.Text
                , cmbCity.SelectedValue
                , txtLocation.Text
                , txtRemark.Text
                , ssMng.EmpSeqI
                );

            ClearControl();
            UpdateUI("Save");            
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            actBLL.Update(txtActivitySeq.Text
                , Int32.Parse(cmbProject.SelectedValue)
                , "" //txtActivityDesc.Text
                , cbActivityType.SelectedValue
                , cmbJobSite.SelectedValue
                , txtAct_Limit.Text
                , string.IsNullOrEmpty(txtDateSignStart.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtDateSignStart.GetStringValue())
                , string.IsNullOrEmpty(txtDateSignEnd.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtDateSignEnd.GetStringValue())
                , txtAppDateStart.GetDateValue()
                , txtAppDateEnd.GetDateValue()
                , txtDateStart.GetDateValue()
                , txtDateEnd.GetDateValue()
                , txtTimeSignEnd.Text
                , cmbCity.SelectedValue
                , txtLocation.Text
                , txtRemark.Text
                , ssMng.EmpSeq);

            ClearControl();
            UpdateUI("Save");
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearControl();
            UpdateUI("Cancel");
        }
        protected void ClearControl()
        {
            //txtActivityDesc.Text= "";
            cmbProject.Text = string.Empty;
            cbActivityType.Text = string.Empty;
            cmbJobSite.Text = string.Empty;
            txtAct_Limit.Text = "";
            txtDateEnd.SetValue("");
            txtDateSignEnd.SetValue("");
            txtDateSignStart.SetValue("");
            txtDateStart.SetValue("");
            txtTimeSignEnd.Text = "";
            txtAppDateStart.SetValue("");
            txtAppDateEnd.SetValue("");
            txtAttendCount.Text = "";
            txtRemark.Text = "";

            LoadDataGrid();
        }
        protected void UpdateUI(string strCommand)
        {
            switch (strCommand)
            {
                case "Save":
                    PanelGrid.Visible = true;
                    PanelAddData.Visible = false;

                    break;

                case "AddNew":
                    PanelGrid.Visible = false;
                    PanelAddData.Visible = true;
                    btnUpdate.Visible = false;
                    btnSave.Visible = true;

                    break;
                case "Cancel":
                    PanelGrid.Visible = true;
                    PanelAddData.Visible = false;
                    break;

                case "Update":
                    PanelGrid.Visible = false;
                    PanelAddData.Visible = true;
                    btnSave.Visible = false;
                    btnUpdate.Visible = true;
                    break;
            }
        }

        protected void cmbProject_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            Nullable<int> BgmProject = string.IsNullOrEmpty(cmbProject.SelectedValue) ? (int?)null : Int32.Parse(cmbProject.SelectedValue);

            DataSet ds = bgmProjBLL.LoadBgmProjects(BgmProject, (int?)null, (int?)null, (int?)null, "");
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                cmbJobSite.Items.Add(new RadComboBoxItem(dt.Rows[0]["JOB_SITE_NAME"].ToString(), dt.Rows[0]["JOB_SITE_SEQ"].ToString()));
                cmbJobSite.SelectedValue = dt.Rows[0]["JOB_SITE_SEQ"].ToString();
                txtLocation.Text = dt.Rows[0]["WORK_PLACE"].ToString();
                txtDateStart.SetValue(dt.Rows[0]["START_DATE"]);
                txtDateEnd.SetValue(dt.Rows[0]["END_DATE"]);
                txtAttendCount.Text = dt.Rows[0]["ATTEND_COUNT"].ToString();
            }
            else
            {
                cmbJobSite.Text = string.Empty;
                txtLocation.Text = "";
                txtDateStart.SetValue("");
                txtDateEnd.SetValue("");
                txtAttendCount.Text = "";
            }
        }
        protected void cmdExportExel_Click(object sender, EventArgs e)
        {
            Nullable<int> ActSequence = null;// Int32.Parse(Request.QueryString["Sequence"]);
            Nullable<DateTime> DateStart = string.IsNullOrEmpty(txtStart.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtStart.GetStringValue());
            Nullable<DateTime> DateEnd = string.IsNullOrEmpty(txtEnd.GetStringValue()) ? (DateTime?)null : DateTime.Parse(txtEnd.GetStringValue());

            DataSet ds = ActReqBLL.LoadActivityRequestForExcel(ActSequence, 0, DateStart, DateEnd);
            DataTable dt = null;

            if (ds.Tables.Count > 0)
                dt = ds.Tables[0];

            Excel_FromDataTable(dt);
        }
        private void Excel_FromDataTable(DataTable dtb)
        {
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("content-disposition", "attachment; filename=SearchResult.xls");
            //Response.Charset = "";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            grdExcel.Visible = true;
            grdExcel.DataSource = dtb;
            grdExcel.DataBind();
            grdExcel.RenderControl(hw);

            Response.Write(tw.ToString());
            Response.End();
        }
    }
}
